from myMath import *
from _collections_abc import Iterable,Iterator

# 切片
lst=['a','b','c','d','e','f','g','h']
lst0=lst[1:3] # 从索引1开始到索引3（不包括3）结束
print(lst0)  # 输出: ['b', 'c']
lst0=lst[1:6:2] # 从索引1开始到索引6（不包括6）结束，步长为2
print(lst0)  # 输出: ['b', 'd', 'f']
lst0=lst[::2] # 从头开始到尾结束，步长为2
print(lst0)  # 输出: ['a', 'c', 'e', 'g']
lst0=lst[-3:] # 从倒数第三个元素开始到最后一个元素结束
print(lst0)  # 输出: ['f', 'g', 'h']
tple=(1,2,3,4,5)
tple0=tple[1:3] # 元组也能切片，返还的仍然是元组
print(tple0)  # 输出: (2, 3)
str1='ABCDEFG'
str0=str1[1:3] # 字符串也能切片，返还的仍然是字符串
print(str0)  # 输出: BC

str1=my_trim('   hello world    ') # 调用函数去除首尾空格
print('|%s|' % str1) # 输出: '|hello world|'

# 迭代
dict0={'ben':19,"megumi":20,"sakura":21}
for k in dict0:
    print(k)
for v in dict0.values():
    print(v)
for k,v in dict0.items():
    print(k,v)
    
print(isinstance('abc', Iterable)) # str是否可迭代，应为true
print(isinstance([1,2,3], Iterable)) # list是否可迭代，应为true
print(isinstance(123, Iterable)) # 整数是否可迭代，应为false

for i,v in enumerate(['A','B','C']): # 迭代索引和值
    print(i,v)
    
lst=list(range(5)) # 将range对象转换为list
lst=list('hello') # 将字符串转换为list
lst=[x*x for x in range(5)]
print(lst) # 输出: [0, 1, 4, 9, 16]
lst=[m+str(n) for m in 'ABC' for n in range(3)]
print(lst) # ['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C0', 'C1', 'C2']

lst=[x for x in range(10) if x%2==0] # for后面加入if过滤条件
print(lst) # [0, 2, 4, 6, 8]
lst=[x if x%2==0 else -x for x in range(10)] # for前面加入if-else表达式
print(lst) # [0, -1, 2, -3, 4, -5, 6, -7, 8, -9]

lst=['ABC','HelloWorld',18,'HIT',True]
lst0=[x.lower() if isinstance(x,str) else None for x in lst] # 不建议使用
lst0=[x.lower() for x in lst if isinstance(x,str)]
print(lst0)

g= (x*x for x in range(5)) # 创建生成器对象
print(next(g)) # 0
print(next(g)) # 1
print(next(g)) # 4
print(next(g)) # 9
print(next(g)) # 16
#print(next(g)) # 会抛出StopIteration异常

g= (x*x for x in range(5))
for x in g: # 遍历生成器对象
    print(x)

f=my_fib(7) # 创建生成器对象
print(next(f)) # 1
print(next(f)) # 1
print(next(f)) # 2
print(next(f)) # 3
print(next(f)) # 5
print(next(f)) # 8
print(next(f)) # 13
f=my_fib(7) # 创建生成器对象
for x in f:
    print(x)

f=yanhui_triangles()
n=0
for x in f:
    if n>=10:
        break
    print(x) # 打印前10行杨辉三角
    n+=1


a=0
isinstance(a,Iterable)
isinstance(a,Iterator)

a=(1,'a',True)
for i in a:
    print(i)